<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="search">
      <el-input v-model="searchIpt" placeholder="请输入优惠卷标题" clearable />
      <el-select v-model="searchIpt1" clearable placeholder="请选择优惠卷类型">
        <el-option v-for="(item, index) in GoodsType" :key="index" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="searchIpt2" clearable placeholder="请选择优惠卷状态">
        <el-option v-for="(item, index) in Status" :key="index" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">查找</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="handleAdd">添加</el-button>
      <el-button type="primary" icon="el-icon-download" @click="handleOut">导出</el-button>
    </div>
    <!-- 表格 -->
    <div class="box">
      <el-table v-loading="listLoading" :data="tableData1" highlight-current-row border style="width: 100%">
        <el-table-column fixed prop="id" label="优惠卷ID" sortable align="center" />
        <el-table-column prop="name" label="优惠卷名称" align="center" />
        <el-table-column prop="desc" label="介绍" align="center" />
        <el-table-column prop="tag" label="标签" align="center" />
        <el-table-column prop="min" label="最低消费" align="center">
          <template slot-scope="scope">
            满{{ scope.row.min }}元可用
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="满减金额" align="center">
          <template slot-scope="scope">
            减免{{ scope.row.discount }}元
          </template>
        </el-table-column>
        <el-table-column prop="limit" label="每人限额" align="center" />
        <el-table-column prop="goodsType" label="商品使用范围" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsType == 0" size="medium">全场通用</span>
            <span v-if="scope.row.goodsType == 2" size="medium">指定商品</span>
            <span v-if="scope.row.goodsType == 1" size="medium">指定分类</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="优惠卷类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.type == 0" size="medium">通用领劵</span>
            <span v-if="scope.row.type == 2" size="medium">兑换码</span>
            <span v-if="scope.row.type == 1" size="medium">注册赠券</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="优惠卷数量" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.total == 0" size="medium">不限</span>
            <span v-else>{{ scope.row.total }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0" size="medium">正常</span>
            <span v-if="scope.row.status == 1" size="medium">已过期</span>
            <span v-if="scope.row.status == 2" size="medium">已下架</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="240" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleXq(scope.row.id)">详情</el-button>
            <el-button type="info" size="small" @click="hanldeEdite(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="hanldeDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="20"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" background />
    </div>
    <!--编辑模态框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <div class="content">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm"
          label-position="left">
          <el-form-item label="优惠卷名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="介绍" prop="desc">
            <el-input v-model="ruleForm.desc" />
          </el-form-item>
          <el-form-item label="标签" prop="tag">
            <el-input v-model="ruleForm.tag" />
          </el-form-item>
          <el-form-item label="最低消费" prop="min">
            <el-input v-model="ruleForm.min">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="满减金额" prop="discount">
            <el-input v-model="ruleForm.discount">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人限领" prop="limit">
            <el-input v-model="ruleForm.limit">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="分发类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择级别">
              <el-option label="通用领劵" :value="0" />
              <el-option label="兑换券" :value="2" />
              <el-option label="注册赠券" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="优惠卷数量" prop="total">
            <el-input v-model="ruleForm.total">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="有效期">
            <el-radio-group v-model="ruleForm.timeType">
              <el-radio-button label="0">领券相对天数</el-radio-button>
              <el-radio-button label="1">指定绝对时间</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-show="ruleForm.timeType == 0" label=" " prop="days">
            <el-input v-model="ruleForm.days">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item v-show="ruleForm.timeType == 1" label=" ">
            <el-col :span="11">
              <el-date-picker v-model="ruleForm.startTime" type="datetime" placeholder="选择日期时间" style="width: 100%;"
                @change="tstart" />
            </el-col>
            <el-col :span="2">
              至
            </el-col>
            <el-col :span="11">
              <el-date-picker v-model="ruleForm.endTime" type="datetime" placeholder="选择日期时间" style="width: 100%;"
                @change="tend" />
            </el-col>
          </el-form-item>
          <el-form-item label="商品限制范围" prop="goodsType">
            <el-radio-group v-model="ruleForm.goodsType">
              <el-radio-button label="0">全场通用</el-radio-button>
              <el-radio-button label="1">指定分类</el-radio-button>
              <el-radio-button label="2">指定商品</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-show="ruleForm.goodsType == 1" label=" ">
            <el-cascader v-model="selectedValue" :options="categoryList" @change="handleCategoryChange" placeholder="请选择分类名称"/>
            <el-button size="mini" @click="addDate">添加</el-button>
            <el-table :data="tableData" style="width: 100%;margin-top: 20px;" border>
              <el-table-column align="center" prop="label" label="分类名称" />
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="deleteData(scope.row.value)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item v-show="ruleForm.goodsType == 2" label="">
            <el-select v-model="goodsValue" placeholder="品牌名称/商品货号" @change="goodsArr">
              <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.id">
                <span style="float: left;">{{ item.name }}</span>
                <span style="float: right; color:#8492a6; font-size: 13px;">No.{{ item.goodsSn }}</span>
              </el-option>
            </el-select>
            <el-button size="mini" @click="addData">添加</el-button>
            <el-table :data="formData" style="width:100%;margin-top: 20px;" border>
              <el-table-column prop="name" label="商品名称" min-width="60" align="center" />
              <el-table-column align="center" prop="goodsSn" label="商品编号" width="80" />
              <el-table-column align="center" label="操作" width="60">
                <template slot-scope="scope">
                  <el-button type="text" @click="delDate(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleQx">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupon, createCoupon, updateCoupon, deleteCoupon } from '@/api/tggl/coupon'
import { listCatAndBrand, listGoods } from '@/api/tggl/goods'
import * as XLSX from 'xlsx'
export default {
  data() {
    return {
      dialogVisible: false,
      currentPage: 1,
      searchIpt: '',
      searchIpt1: '',
      searchIpt2: '',
      tableData: [],
      page: 1,
      total: null,
      limit: 20,
      srcList: [],
      title: '',
      selectedValue: [],
      formData: [],
      goodsValue: [],
      categoryList: [],
      tableData1: [],
      goodsList: [],
      brandList: [],
      add: true,
      listLoading: true,
      ruleForm: {
        timeType: 0,
        goodsValue: [],
        days: 0,
        goodsType: 0,
        endTime: undefined,
        startTime: undefined,
        name: '',
        desc: '',
        tag: '',
        min: '',
        discount: '',
        limit: 1,
        type: '',
        total: '',
        addTime: '',
        status: ''
      },
      rules: {
        name: [
          { required: true, message: '广告标题不能为空', trigger: 'blur' }
        ]
      },
      form: {},
      id: null,
      selGoods: null,
      parentDate: null,
      tabList: [],
      tabList1: [],
      GoodsType: [
        {
          value: 0,
          label: '通用领券'
        },
        {
          value: 1,
          label: '注册赠券'
        },
        {
          value: 2,
          label: '兑换码'
        }
      ],
      Status: [
        {
          value: 0,
          label: '正常'
        },
        {
          value: 1,
          label: '已过期'
        },
        {
          value: 2,
          label: '已下架'
        }
      ]

    }
  },
  mounted() {
    this.handleGetList()
  },
  activated() {
    this.handleGetList()
  },
  methods: {
    // 列表
    async handleGetList() {
      const res = await listCoupon({
        page: this.page,
        limit: this.limit,
        sort: 'add_time',
        order: 'desc',
        name: this.searchIpt,
        type: this.searchIpt1,
        status: this.searchIpt2
      })
      console.log(res, '列表')
      this.tableData1 = res.data.list
      this.total = res.data.total
      this.listLoading = false

      listCatAndBrand().then(response => {
        this.categoryList = JSON.parse(JSON.stringify(response.data.categoryList))
        this.categoryList.map(item => {
          return item.children.map(el => {
            return this.tabList.push(el)
          })
        })
        this.categoryList.map(item => {
          const label = item.label
          console.log(label,'00000')
          return item.children.map(el => {
            el.label =  el.label
            return this.tabList1.push(el)
          })
        })
        console.log(this.tabList)
      })
      listGoods({ limit: 0 }).then(response => {
        this.goodsList = response.data.list
      })
    },
    // 搜索
    handleSearch() {
      this.handleGetList()
    },
    // 分页器
    handleSizeChange(val) {
      this.limit = val
      this.handleGetList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.handleGetList()
    },
    // 详情
    handleXq(val) {
      this.$router.push(`coupon/couponDetail?id=${val}`)
    },
    // 添加
    handleAdd() {
      this.dialogVisible = true
      this.title = '创建'
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.tag = ''
      this.ruleForm.min = 0
      this.ruleForm.discount = 0
      this.ruleForm.limit = 1
      this.ruleForm.type = 0
      this.ruleForm.total = 0
      this.ruleForm.timeType = 0
      this.ruleForm.days = 0
      this.ruleForm.goodsType = 0
    },
    // 删除
    hanldeDel(row) {
      deleteCoupon(row).then(res => {
        console.log('del', res)
        this.handleGetList()
        this.$notify({
          title: '成功',
          message: '删除优惠券成功',
          type: 'success'
        })
      })
    },
    // 模态框关闭
    handleClose(done) {
      done()
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.tag = ''
      this.ruleForm.min = 0
      this.ruleForm.discount = 0
      this.ruleForm.limit = 1
      this.ruleForm.type = 0
      this.ruleForm.total = 0
      this.ruleForm.timeType = 0
      this.ruleForm.days = 0
      this.ruleForm.goodsType = 0
    },
    // 编辑
    hanldeEdite(val) {
      console.log('edit', val)
      this.ruleForm = JSON.parse(JSON.stringify(val))
      this.dialogVisible = true
      this.title = '编辑'
    },
    // 确定编辑
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '编辑') {
            // 编辑
            updateCoupon(this.ruleForm).then(res => {
              if (!res) { return }
              this.$notify({
                title: '成功',
                message: '更新优惠券成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.handleGetList()
              if (this.ruleForm.goodsType === '1') {
                this.tableData = this.ruleForm.goodsValue.map(val => {
                  return this.tabList1.filter(item => {
                    return item.value === val
                  })[0]
                })
              } else if (this.ruleForm.goodsType === '2') {
                this.formData = this.ruleForm.goodsValue.map(val => {
                  return this.goodsList.filter(item => {
                    return item.id === val
                  })[0]
                })
              }
            })
          } else {
            createCoupon(this.ruleForm
            ).then(res => {
              if (!res) { return }
              this.$notify({
                title: '成功',
                message: '创建优惠券成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.handleGetList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 取消
    handleQx() {
      this.dialogVisible = false
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.tag = ''
      this.ruleForm.min = 0
      this.ruleForm.discount = 0
      this.ruleForm.limit = 1
      this.ruleForm.type = 0
      this.ruleForm.total = 0
      this.ruleForm.timeType = 0
      this.ruleForm.days = 0
      this.ruleForm.goodsType = 0
    },
    // 联级选择器
    handleCategoryChange() {
      this.parentDate = JSON.parse(JSON.stringify(this.tabList.filter(item => {
        return item.value === this.selectedValue[1]
      })[0]))
      console.log(this.parentDate)
    },
    // 添加
    addDate() {
      this.parentDate.label = this.tabList.filter(item => {
        return item.value === this.selectedValue[1]
      })[0].label
      this.tableData.push(this.parentDate)
      this.selectedValue = null
    },
    // 商品选择框变化数据
    goodsArr(id) {
      this.selGoods = this.goodsList.filter(item => {
        return item.id === id
      })[0]
    },
    // 删除联级选择器下的表格
    deleteData(value) {
      this.tableData = this.tableData.filter(item => {
        return item.value !== value
      })
    },
    // 删除表格项目
    delDate(id) {
      console.log(id)
      this.formData = this.formData.filter(item => {
        return item.id !== id
      })
    },
    // 添加到表格
    addData() {
      this.formData.push(this.selGoods)
      this.goodsValue = null
      console.log(this.formData)
    },
    // 开始时间
    tstart() {
      this.ruleForm.startTime = this.changeTime(this.ruleForm.startTime)
    },
    // 结束时间
    tend() {
      this.ruleForm.endTime = this.changeTime(this.ruleForm.endTime)
    },
    // 修改时间
    changeTime(time) {
      const datetime = new Date(time)
      const year = datetime.getFullYear()
      const month = datetime.getMonth()
      const date = datetime.getDate()
      const hour = datetime.getHours()
      const minute = datetime.getMinutes()
      const second = datetime.getSeconds()

      const result = year +
        '-' +
        ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
        '-' +
        ((date + 1) < 10 ? '0' + date : date) +
        ' ' +
        ((hour + 1) < 10 ? '0' + hour : hour) +
        ':' +
        ((minute + 1) < 10 ? '0' + minute : minute) +
        ':' +
        ((second + 1) < 10 ? '0' + second : second)
      return result
    },

    // 导出
    handleOut() {
      // 点击导出的时候把现有数据生成一个新的数组 以中文作为key然后在导出

      const demo = []
      for (let i = 0; i < this.tableData1.length; i++) {
        const obje = {
          '优惠券ID': this.tableData1[i].id,
          '名称': this.tableData1[i].name,
          '内容': this.tableData1[i].desc,
          '标签': this.tableData1[i].tag,
          '最低消费': this.tableData1[i].min,
          '减免金额': this.tableData1[i].discount,
          '每人限领': this.tableData1[i].limit,
          '优惠券数量': this.tableData1[i].total
        }

        demo.push(obje)
      }
      console.log(demo)
      // 这里面传入要导出的表格数据
      const worksheet = XLSX.utils.json_to_sheet(demo)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, 'data')
      XLSX.writeFile(workbook, '优惠券信息.xlsx')
    }
  }
}
</script>

<style>
.app-container {
  padding: 20px;
}

/* 输入框 */
.el-input__inner {
  font-size: 12px;
  height: 28px;
  line-height: 28px;
}

.el-form-item {
  margin-bottom: 5px;
}

.el-range-editor.el-input__inner {
  height: 28px;
  vertical-align: middle;
}

/* 按钮 */
.el-button {
  font-size: 12px;
  padding: 7px 15px;
}

/* 表格 */
.el-table {
  font-size: 12px;
  margin-top: 20px;
}

.el-table td,
.el-table th {
  padding: 6px 0;
}

.el-tag {
  height: 20px;
  line-height: 19px;
}

.el-dialog__body {
  padding: 30px 55px;
}

.search {
  display: flex;
  margin-bottom: 10px;
}

.search>.el-input {
  width: 200px;
  /* margin-right: 20px; */
}

/* .search>.el-select {
      margin-right: 10px;
    } */
  /* .content>.el-input__inner{
    width: 300px;
    } */
    .el-form-item__content{
      width: 300px;
    }
.content>.el-input--mini {
  width: 300px;
}

.page {
  text-align: left;
  margin-top: 30px;
  padding: 32px 16px;
}

.el-table th.el-table__cell.is-leaf,
.el-table td.el-table__cell {
  text-align: center;
}

.el-button--text {
  border: 1px solid #1890ff;
  background-color: #1890ff;
  color: #fff;
  padding: 10px;
}

.table-expand label {
  width: 100px;
  color: #99a9bf;
}

.el-form-item__label {
  text-align: left !important;
}
.el-radio-button__inner{
  padding: 7px 15px;
  font-size: 12px;
}
</style>